package com.example.actordemo3.client;

import akka.actor.*;
import akka.cluster.client.ClusterClient;
import akka.cluster.client.ClusterClientSettings;
import akka.cluster.client.ClusterClients;
import akka.cluster.client.ContactPoints;
import com.typesafe.config.ConfigFactory;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ClientStart extends AbstractActor {

    Set<ActorPath> initialContacts() {
        List<ActorPath> actorPaths = Arrays.asList(
                ActorPaths.fromString("akka.tcp://sys@127.0.0.1:2552/system/receptionist"),
                ActorPaths.fromString("akka.tcp://sys@127.0.0.1:2553/system/receptionist"),
                ActorPaths.fromString("akka.tcp://sys@127.0.0.1:2554/system/receptionist"));
        return new HashSet<>(actorPaths);
    }
    ActorRef actorRef = null;
    @Override
    public void preStart() throws Exception {
         actorRef = getContext().system().actorOf(ClusterClient
                 .props(ClusterClientSettings.create(getContext().system())
                .withInitialContacts(initialContacts())), "client");

    }

    @Override
    public Receive createReceive() {
        return receiveBuilder().match(ContactPoints.class,msg->{
            System.out.println("ContactPoints"+msg);
        }).matchAny(o->{
            System.out.println("client");
            actorRef.tell(new ClusterClient.SendToAll("/user/clientDemo",o),getSelf());
        }).build();
    }

    public static void main(String[] args) {
        ActorSystem actorSystem = ActorSystem
                .create("sys1", ConfigFactory.load("cluster4.conf"));

        ActorRef actorRef = actorSystem.actorOf(Props.create(ClientStart.class), "clientStart");

        actorRef.tell("qsx",ActorRef.noSender());
    }


}
